<template>
  <j-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item label="领料单号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="系统自动生成" disabled v-decorator="['requisitionNo']" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="关联订单" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag
                placeholder="请选择关联订单"
                v-decorator="['orderId']"
                dict="oms_product_sales_order,order_no,id"
                @change="handleOrderChange"
                :disabled="disableOrderEdit"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="订单编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="选择订单后自动带出" disabled v-decorator="['orderNo']" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="优化类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                placeholder="请选择优化类型"
                v-decorator="['optimizationSoftwareType']"
                dictCode="optimization_software_type"
                @change="handleSoftwareTypeChange"
                :disabled="disableOrderEdit"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea placeholder="请输入备注" v-decorator="['remark']" :rows="1" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-upload
                v-decorator="['attachments']"
                :file-upload-url="uploadUrl"
                :text="'上传附件'"
                :number="5"
                :token="token"
                :data="uploadParams"
                @change="handleAttachmentChange"
              ></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>

      <!-- 型材明细表格 -->
      <div v-if="showProfileTable">
        <div class="table-operator" style="margin-top: 20px; margin-bottom: 10px">
          <a-divider orientation="center">型材明细</a-divider>
          <a-button type="primary" icon="plus" @click="handleAddProfile">添加型材</a-button>
          <a-button
            type="danger"
            icon="delete"
            @click="handleBatchDeleteProfile"
            :disabled="selectedProfileRowKeys.length === 0"
            >批量删除</a-button
          >
        </div>

        <a-table
          ref="profileTable"
          size="middle"
          bordered
          rowKey="id"
          :columns="profileColumns"
          :dataSource="profileDataSource"
          :pagination="false"
          :rowSelection="{ selectedRowKeys: selectedProfileRowKeys, onChange: onProfileSelectChange }"
        >
          <span slot="action" slot-scope="text, record, index">
            <a @click="handleEditProfile(record, index)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定删除吗?" @confirm="() => handleDeleteProfile(record, index)">
              <a>删除</a>
            </a-popconfirm>
          </span>
        </a-table>
      </div>

      <!-- 配件明细表格 -->
      <div v-if="showAccessoryTable">
        <div class="table-operator" style="margin-top: 20px; margin-bottom: 10px">
          <a-divider orientation="center">配件明细</a-divider>
          <a-button type="primary" icon="plus" @click="handleAddAccessory">添加配件</a-button>
          <a-button
            type="danger"
            icon="delete"
            @click="handleBatchDeleteAccessory"
            :disabled="selectedAccessoryRowKeys.length === 0"
            >批量删除</a-button
          >
        </div>

        <a-table
          ref="accessoryTable"
          size="middle"
          bordered
          rowKey="id"
          :columns="accessoryColumns"
          :dataSource="accessoryDataSource"
          :pagination="false"
          :rowSelection="{ selectedRowKeys: selectedAccessoryRowKeys, onChange: onAccessorySelectChange }"
        >
          <span slot="action" slot-scope="text, record, index">
            <a @click="handleEditAccessory(record, index)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定删除吗?" @confirm="() => handleDeleteAccessory(record, index)">
              <a>删除</a>
            </a-popconfirm>
          </span>
        </a-table>
      </div>
    </a-spin>

    <!-- 型材明细表单弹窗 -->
    <profile-form-modal ref="profileFormModal" @ok="profileFormOk"></profile-form-modal>

    <!-- 配件明细表单弹窗 -->
    <accessory-form-modal ref="accessoryFormModal" @ok="accessoryFormOk"></accessory-form-modal>
  </j-modal>
</template>

<script>
import { FormMixin } from '@/mixins/formMixin'
import { getAction, postAction } from '@/api/manage'
import JDate from '@/components/jeecg/JDate'
import JSearchSelectTag from '@/components/dict/JSearchSelectTag'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import ProfileFormModal from './ProfileFormModal'
import AccessoryFormModal from './AccessoryFormModal'
import JUpload from '@/components/jeecg/JUpload'
import Vue from 'vue'

// 使用require方式导入uuid
const uuidv4 = require('uuid').v4

export default {
  name: 'RequisitionModal',
  mixins: [FormMixin],
  components: {
    JDate,
    JSearchSelectTag,
    JDictSelectTag,
    ProfileFormModal,
    AccessoryFormModal,
    JUpload,
  },
  data() {
    return {
      // 不要使用this.$form.createForm(this)，这会导致循环引用
      // 在mounted钩子中初始化form
      form: null,
      title: '添加领料单',
      visible: false,
      model: {},
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      confirmLoading: false,
      disableOrderEdit: false,

      // 型材明细相关
      profileDataSource: [],
      selectedProfileRowKeys: [],
      profileColumns: [
        { title: '型材编号', dataIndex: 'profileCode', align: 'center' },
        { title: '型材名称', dataIndex: 'profileName', align: 'center' },
        { title: '颜色', dataIndex: 'color', align: 'center' },
        { title: '长度(mm)', dataIndex: 'length', align: 'center' },
        { title: '宽度(mm)', dataIndex: 'width', align: 'center' },
        { title: '高度(mm)', dataIndex: 'height', align: 'center' },
        { title: '数量(根)', dataIndex: 'quantity', align: 'center' },
        { title: '重量(kg)', dataIndex: 'weight', align: 'center' },
        { title: '备注', dataIndex: 'remark', align: 'center' },
        { title: '操作', dataIndex: 'action', align: 'center', scopedSlots: { customRender: 'action' } },
      ],

      // 配件明细相关
      accessoryDataSource: [],
      selectedAccessoryRowKeys: [],
      accessoryColumns: [
        { title: '配件编号', dataIndex: 'accessoryCode', align: 'center' },
        { title: '配件名称', dataIndex: 'accessoryName', align: 'center' },
        { title: '规格', dataIndex: 'specification', align: 'center' },
        { title: '数量', dataIndex: 'quantity', align: 'center' },
        { title: '长度/数量', dataIndex: 'lengthQuantity', align: 'center' },
        { title: '单位', dataIndex: 'unit', align: 'center' },
        { title: '品牌', dataIndex: 'brand', align: 'center' },
        { title: '操作', dataIndex: 'action', align: 'center', scopedSlots: { customRender: 'action' } },
      ],

      url: {
        add: '/wms/requisition/add',
        edit: '/wms/requisition/edit',
        getOrderInfo: '/oms/productSalesOrder/queryById',
        getOrderItems: '/oms/productSalesOrder/getItemsByOrderId',
      },

      // 控制表格显示
      showProfileTable: true,
      showAccessoryTable: true,
      uploadUrl: window._CONFIG['domianURL'] + '/wms/requisition/attachment/upload',
      token: '',
      attachments: [],
      uploadParams: {},
    }
  },
  mounted() {
    // 在mounted钩子中初始化表单，避免循环引用
    this.form = this.$form.createForm(this)
  },
  created() {
    this.token = Vue.ls.get('Access-Token')
  },
  methods: {
    // 初始化表单
    add() {
      this.edit({})
    },
    edit(record) {
      // 确保form已经初始化
      if (!this.form) {
        this.form = this.$form.createForm(this)
      }

      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true

      // 设置标题
      this.title = this.model.id ? '编辑领料单' : '添加领料单'

      // 清空明细数据
      this.profileDataSource = []
      this.selectedProfileRowKeys = []
      this.accessoryDataSource = []
      this.selectedAccessoryRowKeys = []

      // 默认显示两个表格
      this.showProfileTable = true
      this.showAccessoryTable = true

      // 如果是编辑，加载明细数据
      if (this.model.id) {
        // 设置表单值
        this.$nextTick(() => {
          this.form.setFieldsValue(this.model)

          // 如果已关联订单，则禁用订单相关字段编辑
          if (this.model.orderId) {
            this.disableOrderEdit = true
          } else {
            this.disableOrderEdit = false
          }

          // 加载型材明细
          getAction(`/wms/requisition/getProfileList/${this.model.id}`).then((res) => {
            if (res.success) {
              this.profileDataSource = res.result || []
            }
          })

          // 加载配件明细
          getAction(`/wms/requisition/getAccessoryList/${this.model.id}`).then((res) => {
            if (res.success) {
              this.accessoryDataSource = res.result || []
            }
          })
        })
      }

      // 设置上传参数
      this.uploadParams = {
        requisitionId: record.id || '',
        token: this.token,
      }
    },

    // 关闭弹窗
    close() {
      this.$emit('close')
      this.visible = false
    },

    // 提交表单
    handleOk() {
      const that = this

      // 表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          // 检查明细表是否有数据
          if (this.profileDataSource.length === 0 && this.accessoryDataSource.length === 0) {
            this.$message.warning('请至少添加一项型材或配件明细!')
            return
          }

          that.confirmLoading = true

          // 构建提交数据 - 符合WmsRequisitionVO的格式
          let basicInfo = Object.assign({}, this.model, values)
          let formData = {
            requisition: basicInfo,
            profileList: this.profileDataSource,
            accessoryList: this.accessoryDataSource,
          }

          // 提交表单
          let httpUrl = this.url.add
          let method = 'post'

          if (this.model.id) {
            httpUrl = this.url.edit
            method = 'put'
          }

          // 发送请求
          postAction(httpUrl, formData)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                that.close()
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },

    // 选择订单后的回调
    handleOrderChange(value) {
      if (value) {
        // 获取订单信息
        getAction(`${this.url.getOrderInfo}?id=${value}`).then((res) => {
          if (res.success && res.result) {
            // 设置订单编号
            this.form.setFieldsValue({
              orderNo: res.result.orderNo,
              optimizationSoftwareType: res.result.optimizationSoftwareType,
            })

            // 根据优化软件类型设置表格显示
            this.handleSoftwareTypeChange(res.result.optimizationSoftwareType)

            // 获取订单明细，预填充领料单明细
            this.loadOrderItems(value, res.result.optimizationSoftwareType)
          }
        })
      } else {
        this.form.setFieldsValue({
          orderNo: '',
          optimizationSoftwareType: undefined,
        })

        // 清空明细数据
        this.profileDataSource = []
        this.accessoryDataSource = []
      }
    },

    // 加载订单明细
    loadOrderItems(orderId, softwareType) {
      console.log(1111111111111111111111111111111111, orderId)

      if (!orderId) return

      getAction(`${this.url.getOrderItems}?orderId=${orderId}`).then((res) => {
        if (res.success && res.result) {
          // 根据软件类型处理不同的明细数据
          if (softwareType === '0') {
            // 长风
            // 处理型材明细
            if (res.result.profiles && res.result.profiles.length > 0) {
              this.profileDataSource = res.result.profiles.map((item) => {
                return {
                  id: uuidv4(),
                  profileCode: item.profileCode,
                  profileName: item.profileName,
                  color: item.color,
                  length: item.length,
                  width: item.width,
                  height: item.height,
                  quantity: item.quantity,
                  weight: item.weight,
                  remark: '',
                  status: 0,
                }
              })
            }

            // 处理配件明细
            if (res.result.accessories && res.result.accessories.length > 0) {
              this.accessoryDataSource = res.result.accessories.map((item) => {
                return {
                  id: uuidv4(),
                  windowNo: item.windowNo,
                  accessoryCode: item.accessoryCode,
                  accessoryName: item.accessoryName,
                  specification: item.specification,
                  quantity: item.quantity,
                  lengthQuantity: item.lengthQuantity,
                  unit: item.unit,
                  brand: item.brand,
                  status: 0,
                }
              })
            }
          } else if (softwareType === '1') {
            // 新格尔
            // 处理型材明细 (新格尔可能有不同的字段)
            if (res.result.xingerProfiles && res.result.xingerProfiles.length > 0) {
              this.profileDataSource = res.result.xingerProfiles.map((item) => {
                return {
                  id: uuidv4(),
                  profileCode: item.materialCode,
                  profileName: item.materialName,
                  color: item.color || '',
                  length: item.length,
                  width: item.width || 0,
                  height: item.height || 0,
                  quantity: item.quantity,
                  weight: item.weight || 0,
                  remark: '',
                  status: 0,
                }
              })
            }

            // 处理配件明细 (新格尔可能有不同的字段)
            if (res.result.xingerAccessories && res.result.xingerAccessories.length > 0) {
              this.accessoryDataSource = res.result.xingerAccessories.map((item) => {
                return {
                  id: uuidv4(),
                  windowNo: item.windowNo || '',
                  accessoryCode: item.accessoryCode,
                  accessoryName: item.accessoryName,
                  specification: item.specification || '',
                  quantity: item.quantity,
                  lengthQuantity: item.lengthQuantity || '',
                  unit: item.unit || '个',
                  brand: item.brand || '',
                  status: 0,
                }
              })
            }
          }
        }
      })
    },

    // 优化软件类型变更
    handleSoftwareTypeChange(value) {
      if (type == '0') {
        // 长风
        this.showProfileTable = true
        this.showAccessoryTable = true

        // 调整型材列
        this.profileColumns = [
          { title: '型材编号', dataIndex: 'profileCode', align: 'center' },
          { title: '型材名称', dataIndex: 'profileName', align: 'center' },
          { title: '颜色', dataIndex: 'color', align: 'center' },
          { title: '长度(mm)', dataIndex: 'length', align: 'center' },
          { title: '宽度(mm)', dataIndex: 'width', align: 'center' },
          { title: '高度(mm)', dataIndex: 'height', align: 'center' },
          { title: '数量(根)', dataIndex: 'quantity', align: 'center' },
          { title: '重量(kg)', dataIndex: 'weight', align: 'center' },
          { title: '备注', dataIndex: 'remark', align: 'center' },
          { title: '领料状态', dataIndex: 'status', align: 'center', scopedSlots: { customRender: 'statusSlot' } },
        ]

        // 调整配件列
        this.accessoryColumns = [
          { title: '配件编号', dataIndex: 'accessoryCode', align: 'center' },
          { title: '配件名称', dataIndex: 'accessoryName', align: 'center' },
          { title: '规格', dataIndex: 'specification', align: 'center' },
          { title: '数量', dataIndex: 'quantity', align: 'center' },
          { title: '单位', dataIndex: 'unit', align: 'center' },
          { title: '品牌', dataIndex: 'brand', align: 'center' },
          { title: '领料状态', dataIndex: 'status', align: 'center', scopedSlots: { customRender: 'statusSlot' } },
        ]
      } else if (type == '1') {
        // 新格尔
        this.showProfileTable = true
        this.showAccessoryTable = true

        // 调整型材列 (新格尔可能需要不同的列)
        this.profileColumns = [
          { title: '型材编号', dataIndex: 'profileCode', align: 'center' },
          { title: '型材名称', dataIndex: 'profileName', align: 'center' },
          { title: '颜色', dataIndex: 'color', align: 'center' },
          { title: '数量(根)', dataIndex: 'quantity', align: 'center' },
          { title: '长度(mm)', dataIndex: 'length', align: 'center' },
          { title: '重量(kg)', dataIndex: 'weight', align: 'center' },
          { title: '备注', dataIndex: 'remark', align: 'center' },
          { title: '领料状态', dataIndex: 'status', align: 'center', scopedSlots: { customRender: 'statusSlot' } },
        ]

        // 调整配件列 (新格尔可能需要不同的列)
        this.accessoryColumns = [
          { title: '配件编号', dataIndex: 'accessoryCode', align: 'center' },
          { title: '配件名称', dataIndex: 'accessoryName', align: 'center' },
          { title: '长度/数量', dataIndex: 'lengthQuantity', align: 'center' },
          { title: '单位', dataIndex: 'unit', align: 'center' },
          { title: '领料状态', dataIndex: 'status', align: 'center', scopedSlots: { customRender: 'statusSlot' } },
        ]
      }
    },

    // 型材表格行选择变化
    onProfileSelectChange(selectedRowKeys) {
      this.selectedProfileRowKeys = selectedRowKeys
    },

    // 配件表格行选择变化
    onAccessorySelectChange(selectedRowKeys) {
      this.selectedAccessoryRowKeys = selectedRowKeys
    },

    // 添加型材明细
    handleAddProfile() {
      const softwareType = this.form.getFieldValue('optimizationSoftwareType')
      if (!softwareType) {
        this.$message.warning('请先选择优化软件类型!')
        return
      }

      this.$refs.profileFormModal.add(softwareType)
    },

    // 编辑型材明细
    handleEditProfile(record, index) {
      const softwareType = this.form.getFieldValue('optimizationSoftwareType')
      this.$refs.profileFormModal.edit(record, softwareType, index)
    },

    // 删除型材明细
    handleDeleteProfile(record, index) {
      this.profileDataSource = this.profileDataSource.filter((item, i) => i !== index)
    },

    // 批量删除型材明细
    handleBatchDeleteProfile() {
      if (this.selectedProfileRowKeys.length === 0) return

      this.profileDataSource = this.profileDataSource.filter((item) => !this.selectedProfileRowKeys.includes(item.id))
      this.selectedProfileRowKeys = []
    },

    // 添加配件明细
    handleAddAccessory() {
      const softwareType = this.form.getFieldValue('optimizationSoftwareType')
      if (!softwareType) {
        this.$message.warning('请先选择优化软件类型!')
        return
      }

      this.$refs.accessoryFormModal.add(softwareType)
    },

    // 编辑配件明细
    handleEditAccessory(record, index) {
      const softwareType = this.form.getFieldValue('optimizationSoftwareType')
      this.$refs.accessoryFormModal.edit(record, softwareType, index)
    },

    // 删除配件明细
    handleDeleteAccessory(record, index) {
      this.accessoryDataSource = this.accessoryDataSource.filter((item, i) => i !== index)
    },

    // 批量删除配件明细
    handleBatchDeleteAccessory() {
      if (this.selectedAccessoryRowKeys.length === 0) return

      this.accessoryDataSource = this.accessoryDataSource.filter(
        (item) => !this.selectedAccessoryRowKeys.includes(item.id)
      )
      this.selectedAccessoryRowKeys = []
    },

    // 型材表单确认
    profileFormOk(formData, index) {
      if (index !== undefined) {
        // 编辑
        this.$set(this.profileDataSource, index, formData)
      } else {
        // 新增
        this.profileDataSource.push(formData)
      }
    },

    // 配件表单确认
    accessoryFormOk(formData, index) {
      if (index !== undefined) {
        // 编辑
        this.$set(this.accessoryDataSource, index, formData)
      } else {
        // 新增
        this.accessoryDataSource.push(formData)
      }
    },

    // 处理附件变更
    handleAttachmentChange(fileList) {
      this.attachments = fileList
      console.log('附件列表:', this.attachments)
    },
  },
}
</script>

<style scoped>
</style> 